import hashlib

from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.shortcuts import redirect, render
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt

from login.user.forms import RegisterForm, UserForm


def index(request):
	"""
	主页
	"""
	return render(request, 'base.html')


def user_login(request):
	"""
	登录
	"""
	if request.method == 'POST':
		login_form = UserForm(request.POST)
		if login_form.is_valid():
			# 请求时清楚安全数据
			username = login_form.cleaned_data['username']
			password = login_form.cleaned_data['password']
			# 匹配用户信息
			user = authenticate(username=username, password=password)
			if user:
				# 自动登录并存储session
				login(request, user)
				return redirect('/')
			else:
				messages.error(request, '账号或密码输入错误')
		else:
			return render(request, 'user/login.html', locals())
	else:
		login_form = UserForm()
	return render(request, 'user/login.html', locals())


def user_register(request):
	"""
	注册
	"""
	if request.method == 'POST':
		register_form = RegisterForm(request.POST)
		if register_form.is_valid():
			data = register_form.cleaned_data
			if data.get('password1') != data.get('password2'):
				messages.error(request, '密码输入不一致，请重新输入')
				return redirect('login:register')
			else:
				same_name = User.objects.filter(username=data.get('username'))
				if same_name:
					messages.error(request, '用户名已存在，请重新输入')
					return redirect('login:register')
				same_email = User.objects.filter(email=data.get('email'))
				if same_email:
					messages.error(request, '邮箱已被注册，请重新输入')
					return redirect('login:register')
				# 注意创建用户用法
				new_user = User.objects.create_user(username=data.get('username'), password=data.get('password2'),
				                                    email=data.get('email'))
				new_user.save()
				messages.success(request, '注册成功，现在可以登陆啦')
				return redirect('login:login')
	else:
		register_form = RegisterForm()
	return render(request, 'user/register.html', locals())


def user_logout(request):
	"""
	登出
	"""
	logout(request)
	return redirect('/')
